package com.gwd.task.controller;

import com.gwd.task.model.FilesUploadDTO;
import com.gwd.task.model.PageUtils;
import com.gwd.task.services.AttachmentServer;
import com.gwd.task.services.FileLookupMarkServer;
import com.gwd.task.services.FilesUploadServer;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @author zhiyongming
 * @date 2021/1/26 10:50
 */
@RestController
@RequestMapping(value = "/v1/filesUpload")
public class FilesUploadController {
    @Resource
    private FilesUploadServer filesUploadServer;
    @Resource
    private FileLookupMarkServer fileLookupMarkServer;
    @Resource
    private AttachmentServer attachmentServer;

    @GetMapping(value = "/findByPage")
    public PageUtils findByPage(@Validated FilesUploadDTO dto, PageUtils pageUtils, @RequestAttribute("userId") Long userId) {
        return filesUploadServer.findByPage(dto, pageUtils, userId);
    }

    @PostMapping(value = "/save")
    public void save(@Validated @RequestBody FilesUploadDTO dto, @RequestAttribute("userId") Long userId) {
        filesUploadServer.save(dto, userId);
    }

    @GetMapping(value = "/download")
    public void export(@RequestParam String fileCode, String fileName, HttpServletResponse response, @RequestAttribute("userId") Long userId) {
        if (fileName.equals("")) {
            fileName = attachmentServer.findByFileName(fileCode).getOriginalFilename();
        } else {
            fileLookupMarkServer.changeState(fileCode, userId);
        }
        String path = "E:\\files\\" + fileCode;
        try{ //写入浏览器
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-Type", "text/html;charset=utf-8");
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            OutputStream outputStream = response.getOutputStream();
            FileInputStream fis = new FileInputStream(new File(path));
            int len ;
            byte[] bytes = new byte[1024];
            while ((len = fis.read(bytes))!=-1) {
                outputStream.write(bytes,0, len);
            }
            fis.close();
            outputStream.flush();
            outputStream.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    }
